<!--
 * @Author: your name
 * @Date: 2020-12-08 16:59:08
 * @LastEditTime: 2020-12-08 21:13:43
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue_shop\src\components\ActivitesList.vue
-->
<template>
  <div class="ActivitiesList-card-main">
    <h2> 活动列表</h2><br />
    <el-button type="primary" @click="newActivities">申请活动</el-button>
    <el-card class="activitieInfo" shadow="hover" v-for="activitie in activitieInfoList" :key="activitie.id">
      <p>{{activitie.id}}</p>
      <p>{{activitie.author_id}}</p>
      <p>{{activitie.author_name}}</p>
      <p>{{activitie.title}}</p>
      <p>{{activitie.content}}</p>
      <p>附件信息:
        <span class="file-name" v-for="file in  JSON.parse(activitie.files)" :key="file.id"
          @click="download(file.id,file.file_type)">{{file.original_name}}</span>
      </p>
    </el-card>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        activitieInfoList: []
      };
    },
    created() {
      this.getActivitieInfoList()
    },
    methods: {
      getActivitieInfoList: async function () {
        const {
          data: res
        } = await this.$http.get('/activities')
        if (res.meta.success == false) return this.$message.error(res.meta.message)
        this.activitieInfoList = res.data
      },
      download: async function (id, file_type) {
        if (!id) {
          return
        }
        const res = await this.$http.get('/files/download/' + id, {
          id
        }, {
          responseType: 'blob'
        })
        if (res.status != 200) return this.$message.error('文件下载失败')
        if (res.status == 200) {
          this.downloadFile(res.data, Date.parse(new Date()) + file_type)
        }

      },
      newActivities: function () {
        this.$router.push('/activites/new')
      },
      downloadFile(content, filename) {
        const blob = new Blob([content]) //创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
        const url = window.URL.createObjectURL(blob) //URL.createObjectURL(object)表示生成一个File对象或Blob对象
        let dom = document.createElement('a') //设置一个隐藏的a标签，href为输出流，设置download
        dom.style.display = 'none'
        dom.href = url
        dom.setAttribute('download', filename) //指示浏览器下载url,而不是导航到它；因此将提示用户将其保存为本地文件
        document.body.appendChild(dom)
        dom.click()
      }
    }
  }

</script>

<style lang="less">
  .ActivitiesList-card-main {
    width: 100%;

    .file-name {
      cursor: pointer;
    }

    .file-name:hover {
      color: blue;
    }
  }

</style>
